package com.config;

import com.util.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 全局异常处理
 *
 * @author: keke
 * @date: 2021/12/1
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public void exceptionHandler(HttpServletResponse response, Exception e) {
        if (e instanceof NullPointerException || e instanceof IllegalArgumentException) {
            String message = e.getMessage();
            writeResponse(response, StringUtils.isEmpty(message) ? getErrorStack(e) : message);
            return;
        }
        writeResponse(response, getErrorStack(e));
    }

    private void writeResponse(HttpServletResponse response, String message) {
        Result<String> result = Result.fail(message);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try {
            response.getWriter().write(JSONUtil.toJsonString(result));
        } catch (IOException e) {
            LOGGER.error("writeResponse error", e);
        }
    }

    private String getErrorStack(Exception e) {
        StringBuilder sb = new StringBuilder();
        StackTraceElement[] stacks = e.getStackTrace();
        for (StackTraceElement stack : stacks) {
            sb.append(stack.toString() + System.lineSeparator());
        }
        return sb.toString();
    }
}
